package com.hummingbird.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hummingbird.portal.dto.QuestionDTO;
import com.hummingbird.portal.exception.ServiceException;
import com.hummingbird.portal.mapper.QuestionTagMapper;
import com.hummingbird.portal.mapper.UserMapper;
import com.hummingbird.portal.mapper.UserQuestionMapper;
import com.hummingbird.portal.pojo.*;
import com.hummingbird.portal.mapper.QuestionMapper;
import com.hummingbird.portal.service.IQuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hummingbird.portal.service.ITagService;
import com.hummingbird.portal.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author -1E18
 * @since 2024-09-22
 */
@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private ITagService tagService;

    @Override
    public PageInfo<Question> getMyQuestions(String username, Integer pageNum, Integer pageSize) {
        User user = userMapper.findUserByUsername(username);
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        queryWrapper.eq("delete_status", 0);
        queryWrapper.orderByDesc("createtime");
        PageHelper.startPage(pageNum, pageSize); // limit 0, 8

        List<Question> questions = questionMapper.selectList(queryWrapper);
        //log.debug("找到当前用户的问题数:{}", questions.size()));

        for (Question question : questions) {
            String tagNames = question.getTagNames();
            String[] tagNamesArr = tagNames.split(",");
            List<Tag> tags = new ArrayList<>();
            for (String tagName : tagNamesArr) {
                Tag tag = tagService.getNameToTagMap().get(tagName);
                tags.add(tag);
            }
            question.setTags(tags);
        }

        /// 封装到
        PageInfo<Question> pageInfo = new PageInfo<>(questions);
        log.info("PageInfo:{}", pageInfo);
        log.info("PageInfo:{}", pageInfo.getList().size());
        return pageInfo;
    }

    @Resource
    private QuestionTagMapper questionTagMapper;

    @Resource
    private UserQuestionMapper userQuestionMapper;

    @Resource
    private IUserService userService;

    @Override
    @Transactional  // 保证下面的代码在同一个事务中执行  原理是AOP-动态代理
    public void saveQuestion(QuestionDTO questionDTO, String username) {
        // 插入问题表、 插入标签问题关联表、 插入问题老师关联表
        User user = userMapper.findUserByUsername(username);
        String[] tagNames = questionDTO.getTagNames();
        StringBuilder builder = new StringBuilder();
        for (String tagName : tagNames) {
            builder.append(tagName).append(",");
        }
        String tags = builder.deleteCharAt(builder.length() - 1).toString();
        Question question = new Question().setTitle(questionDTO.getTitle())
                .setContent(questionDTO.getContent())
                .setTagNames(tags)
                .setUserId(user.getId())
                .setUserNickName(user.getNickname())
                .setDeleteStatus(0)
                .setStatus(0)
                .setPublicStatus(0)
                .setPageViews(0)
                .setCreatetime(LocalDateTime.now());
        int num1 = questionMapper.insert(question);
        if (num1 != 1) {
            throw ServiceException.busy();  // busy - 所有的dbs异常
        }
        log.debug("添加了新的问题： Question{}", question);

        List<Tag> allTags = tagService.getTags();
        for (String tagName : tagNames) {
            Tag tag = tagService.getNameToTagMap().get(tagName);
            QuestionTag questionTag = new QuestionTag().setQuestionId(question.getId())
                    .setTagId(tag.getId())
                    .setQuestionId(question.getId());
            int num2 = questionTagMapper.insert(questionTag);
            if (num2 != 1) {
                throw ServiceException.busy();
            }

            String[] teacherNicknames = questionDTO.getTeacherNicknames();
            for (String teacherNickname : teacherNicknames) {
                User master = userService.getMastersMap().get(teacherNickname);
                UserQuestion userQuestion = new UserQuestion().setQuestionId(question.getId())
                        .setUserId(user.getId())
                        .setQuestionId(question.getId())
                        .setCreatetime(LocalDateTime.now());
                int num3 = userQuestionMapper.insert(userQuestion);
                if (num3 != 1) {
                    throw ServiceException.busy();
                }
            }
        }
    }

    @Override
    public Integer countQuestionByUserId(Integer id) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        queryWrapper.eq("delete_status", 0);
        Integer cnt = questionMapper.selectCount(queryWrapper);
        return cnt;
    }

    @Override
    public PageInfo<Question> getQuestionsByTeacherName(String username, Integer pageNum, Integer pageSize) {
        User user = userMapper.findUserByUsername(username);
        PageHelper.startPage(pageNum, pageSize); // limit 0, 8

        List<Question> questions = questionMapper.findTeacherQuestions(user.getId());
        //log.debug("找到当前用户的问题数:{}", questions.size()));

        for (Question question : questions) {
            String tagNames = question.getTagNames();
            String[] tagNamesArr = tagNames.split(",");
            List<Tag> tags = new ArrayList<>();
            for (String tagName : tagNamesArr) {
                Tag tag = tagService.getNameToTagMap().get(tagName);
                tags.add(tag);
            }
            question.setTags(tags);
        }

        /// 封装到
        PageInfo<Question> pageInfo = new PageInfo<>(questions);
        log.info("PageInfo:{}", pageInfo);
        log.info("PageInfo:{}", pageInfo.getList().size());
        return pageInfo;
    }
}
